import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Canvas, Button, Input } from '@tarojs/components'
import drawQrcode from 'weapp-qrcode'
import './index.scss'

export default class QrCode extends Component {
  constructor(props) {
    super(props)
    this.state = {
      qrText: 'https://example.com',
      scanResult: '',
      canvasId: 'qrcodeCanvas',
      width: 200,
      height: 200,
      currentTheme: 'mint', // 默认主题
      isSaving: false
    }
  }

  componentDidMount() {
    // 加载用户主题偏好
    try {
      const savedTheme = Taro.getStorageSync('user-theme-preference')
      if (savedTheme && (savedTheme === 'mint' || savedTheme === 'cream')) {
        this.setState({ currentTheme: savedTheme })
      }
    } catch (error) {
      console.error('读取主题偏好出错', error)
    }

    this.generateQrCode()
  }

  // 设置分享信息
  onShareAppMessage() {
    return {
      title: '二维码扫描与生成工具，一键搞定所有二维码需求！',
      path: '/pages-qrcode/index',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/code.png'
    }
  }

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '超好用的二维码工具，扫码生成一步到位！',
      query: '',
      imageUrl: 'cloud://cloud1-1ghcuz1u4c694d57.636c-cloud1-1ghcuz1u4c694d57-1304750880/images/code.png'
    }
  }

  generateQrCode = () => {
    const { qrText, canvasId, width, height } = this.state

    // Generate QR code on canvas
    drawQrcode({
      width,
      height,
      canvasId,
      text: qrText,
      // Optional parameters for customization
      background: '#ffffff',
      foreground: '#000000',
      correctLevel: 3 // highest error correction level
    })
  }

  handleTextChange = (e) => {
    this.setState({
      qrText: e.detail.value
    })
  }

  scanQrCode = () => {
    // Use WeChat's native scanning functionality
    Taro.scanCode({
      onlyFromCamera: false, // Allow both camera and image scanning
      scanType: ['qrCode', 'barCode'], // Scan both QR codes and bar codes
      success: (res) => {
        this.setState({
          scanResult: res.result
        })
        Taro.showToast({
          title: '扫码成功',
          icon: 'success',
          duration: 2000
        })
      },
      fail: (err) => {
        console.error('扫码失败', err)
        Taro.showToast({
          title: '扫码失败',
          icon: 'error',
          duration: 2000
        })
      }
    })
  }

  copyResultToClipboard = () => {
    const { scanResult } = this.state
    if (!scanResult) {
      Taro.showToast({
        title: '没有可复制的内容',
        icon: 'none',
        duration: 2000
      })
      return
    }

    Taro.setClipboardData({
      data: scanResult,
      success: () => {
        Taro.showToast({
          title: '复制成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  }

  // 保存二维码到相册
  saveQrCodeToAlbum = async () => {
    const { canvasId } = this.state

    this.setState({ isSaving: true })

    try {
      // 获取用户授权
      const settingRes = await Taro.getSetting()
      if (!settingRes.authSetting['scope.writePhotosAlbum']) {
        await Taro.authorize({ scope: 'scope.writePhotosAlbum' })
      }

      // 将Canvas转换为临时文件
      const canvasRes = await Taro.canvasToTempFilePath({
        canvasId,
        quality: 1
      })

      // 保存图片到相册
      await Taro.saveImageToPhotosAlbum({
        filePath: canvasRes.tempFilePath
      })

      Taro.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 2000
      })
    } catch (error) {
      console.error('保存二维码失败', error)
      Taro.showToast({
        title: '保存失败，请检查授权设置',
        icon: 'none',
        duration: 2000
      })
    } finally {
      this.setState({ isSaving: false })
    }
  }

  // 分享当前二维码
  shareQrCode = () => {
    Taro.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  }

  render() {
    const { qrText, scanResult, currentTheme, isSaving } = this.state

    return (
      <View className={`qrcode-page theme-${currentTheme}`}>
        <View className='card'>
          <View className='card-title'>二维码生成</View>
          <View className='input-area'>
            <Input
              className='input'
              type='text'
              placeholder='请输入文本生成二维码'
              value={qrText}
              onInput={this.handleTextChange}
            />
            <Button className='generate-btn' onClick={this.generateQrCode}>
              生成二维码
            </Button>
          </View>
          <View className='canvas-container'>
            <Canvas
              canvasId={this.state.canvasId}
              className='qrcode-canvas'
              style={{
                width: `${this.state.width}px`,
                height: `${this.state.height}px`
              }}
            />
          </View>
          <View className='button-group'>
            <Button className='save-btn' onClick={this.saveQrCodeToAlbum} loading={isSaving} disabled={isSaving}>
              保存到相册
            </Button>
            {/* <Button className='share-btn' onClick={this.shareQrCode}>
              分享二维码
            </Button> */}
          </View>
        </View>

        <View className='card'>
          <View className='card-title'>二维码扫描</View>
          <Button className='scan-btn' onClick={this.scanQrCode}>
            扫描二维码
          </Button>
          {scanResult && (
            <View className='result-container'>
              <View className='result-title'>扫描结果：</View>
              <View className='result-content'>{scanResult}</View>
              <Button className='copy-btn' onClick={this.copyResultToClipboard}>
                复制结果
              </Button>
            </View>
          )}
        </View>

        <View className='share-card'>
          <View className='share-card-title'>分享给朋友</View>
          <View className='share-card-content'>
            <View className='share-text'>
              「二维码工具，轻松扫一扫」
              <View className='share-desc'>扫码识别，生成分享，一键搞定！</View>
            </View>
            <Button className='share-card-btn' openType='share'>
              立即分享
            </Button>
          </View>
        </View>
      </View>
    )
  }
}
